<template>
  <div
    class="fullscreen-wrapper"
    :class="{ 'is-fullscreen': isFullscreen }"
    ref="container"
  >
    <slot></slot>

    <!-- 全屏控制按钮 -->
<!--    <button-->
<!--      v-if="showControls && isFullscreen"-->
<!--      @click="handleExitRequest"-->
<!--      class="fullscreen-exit-btn"-->
<!--    >-->
<!--      <i class="el-icon-close"></i>-->
<!--      退出全屏-->
<!--    </button>-->

    <!-- 退出确认对话框 -->
    <el-dialog
      title="退出确认"
      :visible.sync="exitDialogVisible"
      width="400px"
      :close-on-click-modal="false"
      :show-close="false"
    >
      <div class="exit-confirm-content">
        <i class="el-icon-warning" style="color: #E6A23C; font-size: 24px; margin-right: 10px;"></i>
        <span>确定要退出全屏模式吗？退出后将结束考试！</span>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="exitDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmExit">确定退出</el-button>
      </div>
    </el-dialog>

    <!-- 切屏警告对话框 -->
    <el-dialog
      title="警告"
      :visible.sync="switchWarningVisible"
      width="450px"
      :close-on-click-modal="false"
      :show-close="false"
    >
      <div class="switch-warning-content">
        <i class="el-icon-warning" style="color: #E6A23C; font-size: 24px; margin-right: 10px;"></i>
        <div>
          <p>检测到您已切换标签页{{ switchCount }}次！</p>
          <p v-if="remainingAttempts > 0">剩余允许切换次数: {{ remainingAttempts }}</p>
          <p v-else style="color: #F56C6C;">您已超过最大切换次数限制！</p>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="switchWarningVisible = false">我知道了</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {logMonitoringEvent} from "@/api/exam/monitoring";

export default {
  name: 'FullscreenContainer',
  props: {
    groupId: [String, Number],
    // 是否自动进入全屏
    autoFullscreen: {
      type: Boolean,
      default: false,
    },
    // 是否显示控制按钮
    showControls: {
      type: Boolean,
      default: true
    },
    // 是否启用防作弊模式
    antiCheating: {
      type: Boolean,
      default: false
    },
    // 允许切屏的最大次数
    maxSwitchCount: {
      type: Number,
      default: 6
    }
  },
  data() {
    return {
      isFullscreen: false,
      styleElement: null,
      overlayElement: null,
      switchCount: 0,
      exitAttempts: 0,
      exitDialogVisible: false,
      switchWarningVisible: false,
      keydownListener: null,
      beforeUnloadListener: null,
      visibilityChangeListener: null,
      blurListener: null,
      focusListener: null
    }
  },
  computed: {
    remainingAttempts() {
      return (this.maxSwitchCount - this.switchCount)/2
    }
  },
  mounted() {
    // 监听全屏变化事件
    document.addEventListener('fullscreenchange', this.handleFullscreenChange)
    document.addEventListener('webkitfullscreenchange', this.handleFullscreenChange)
    document.addEventListener('msfullscreenchange', this.handleFullscreenChange)

    // 防作弊监听
    if (this.antiCheating) {
      this.setupAntiCheating()
    }

    // 添加键盘事件监听
    this.addKeyListeners()

    // 添加页面卸载前监听
    this.beforeUnloadListener = (e) => {
      if (this.isFullscreen) {
        e.preventDefault()
        e.returnValue = '您正在全屏考试中，确定要离开吗？'
        return e.returnValue
      }
    }
    window.addEventListener('beforeunload', this.beforeUnloadListener)

    if (this.autoFullscreen) {
      this.$nextTick(() => {
        this.enterFullscreen()
      })
    }
  },
  beforeDestroy() {
    // 清理事件监听
    this.removeEventListeners()

    // 退出全屏
    if (this.isFullscreen) {
      this.exitFullscreen()
    }

    // 清理添加的元素
    this.removeFullscreenStyles()

    // 移除键盘事件监听
    this.removeKeyListeners()

    // 移除beforeunload监听
    if (this.beforeUnloadListener) {
      window.removeEventListener('beforeunload', this.beforeUnloadListener)
    }
  },
  methods: {
    // 设置防作弊监听
    setupAntiCheating() {
      // 页面可见性变化监听
      this.visibilityChangeListener = () => {
        if (document.hidden) {
          this.handleSwitchDetected()
        }
      }
      document.addEventListener('visibilitychange', this.visibilityChangeListener)

      // 窗口失去焦点监听（备用方案）
      this.blurListener = () => {
        if (this.isFullscreen) {
          this.handleSwitchDetected()
        }
      }
      window.addEventListener('blur', this.blurListener)

      // 窗口获得焦点监听（用于重置状态）
      this.focusListener = () => {
        // 可以在这里添加获得焦点后的处理逻辑
      }
      window.addEventListener('focus', this.focusListener)
    },
    // 在methods中添加以下方法
    async recordMonitoringEvent(eventType, screenshot = null) {
      console.log('记录监考事件')
      try {
        const eventDetails = this.getEventDetails(eventType)
        const deviceInfo = this.getDeviceInfo()

        const logData = {
          examId: this.$route.query.id,
          sessionId: this.$route.query.sessionId,
          groupId: this.groupId,
          eventType: eventType,
          screenshot: screenshot,
          deviceInfo: deviceInfo,
          ipAddress: await this.getIpAddress(),
          eventDetails: eventDetails
        }

        await logMonitoringEvent(logData)
      } catch (error) {
        console.error('记录监考事件失败:', error)
      }
    },

    getEventDetails(eventType) {
      const eventMap = {
        'page-switch': '切换标签页',
        'exit-fullscreen': '退出全屏',
        'keyboard-shortcut': '尝试使用键盘快捷键',
        'exceed-switch-limit': '超过最大切换次数限制'
      }
      return eventMap[eventType] || '未知事件'
    },

    getDeviceInfo() {
      const userAgent = navigator.userAgent
      const screenInfo = `分辨率: ${window.screen.width}x${window.screen.height}`
      return `${userAgent} | ${screenInfo}`
    },

    async getIpAddress() {
      try {
        const response = await fetch('https://api.ipify.org?format=json')
        const data = await response.json()
        return data.ip
      } catch (error) {
        console.error('获取IP地址失败:', error)
        return '未知'
      }
    },

    // 处理检测到的切屏行为
    handleSwitchDetected() {
      this.switchCount++
        this.recordMonitoringEvent('page-switch')

      // 显示警告
      this.switchWarningVisible = true
      this.$emit('cheating-detected', {
        type: 'page-switch',
        count: this.switchCount,
        remaining: this.remainingAttempts
      })

      // 超过最大次数限制
      if (this.switchCount >= this.maxSwitchCount) {
        this.$emit('cheating-detected', {
          type: 'exceed-switch-limit',
          count: this.switchCount
        })
        this.forceExit()
      }
    },

    // 添加键盘事件监听
    addKeyListeners() {
      this.keydownListener = (e) => {
        // 阻止ESC和F11键的默认行为
        if (this.isFullscreen && (e.key === 'Escape' || e.key === 'Esc' || e.keyCode === 27 || e.key === 'F11' || e.keyCode === 122)) {
          e.preventDefault()
          e.stopPropagation()
          this.handleExitAttempt()
        }
      }

      // 使用捕获阶段以确保最先处理
      window.addEventListener('keydown', this.keydownListener, true)
    },

    // 移除键盘事件监听
    removeKeyListeners() {
      if (this.keydownListener) {
        window.removeEventListener('keydown', this.keydownListener, true)
      }
    },

    // 处理退出尝试
    handleExitAttempt() {
      this.exitAttempts++

      if (this.exitAttempts >= this.maxSwitchCount) {
        // 超过最大尝试次数，强制退出
        this.$message.warning(`您已尝试退出全屏${this.exitAttempts}次，将自动提交试卷并退出`)
        this.forceExit()
      } else {
        // 显示警告
        const remaining = this.maxSwitchCount - this.exitAttempts
        this.$message.warning(`考试期间不允许退出全屏模式！剩余警告次数: ${remaining}`)
      }
    },

    // 处理退出请求
    handleExitRequest() {
      this.exitDialogVisible = true
    },

    // 确认退出
    confirmExit() {
      this.exitDialogVisible = false
      this.forceExit()
    },

    // 强制退出全屏并关闭页面
    forceExit() {
      this.exitFullscreen().then(() => {
        this.closePage()
        // 关闭当前标签页
        this.$store.dispatch("tagsView/delView", this.$route)

        // 返回上一页
        this.$router.go(-1)
      })
    },

    // 关闭页面
    closePage() {
      this.$emit('fullscreen-exited')
    },

    // 进入全屏
    enterFullscreen() {
      const element = document.documentElement // 针对整个文档

      // 创建全屏样式
      this.createFullscreenStyles()

      // 标准API
      if (element.requestFullscreen) {
        element.requestFullscreen()
          .then(() => {
            this.forceHideBrowserUI()
          })
          .catch(err => {
            console.error('全屏错误:', err)
            this.fallbackFullscreen()
          })
      }
      // Safari/Chrome旧版
      else if (element.webkitRequestFullscreen) {
        element.webkitRequestFullscreen()
        this.forceHideBrowserUI()
      }
      // IE11
      else if (element.msRequestFullscreen) {
        element.msRequestFullscreen()
        this.forceHideBrowserUI()
      }
      // 不支持的浏览器使用备用方案
      else {
        this.fallbackFullscreen()
      }
    },

    // 退出全屏
    exitFullscreen() {
      return new Promise((resolve) => {
        try {
          if (document.exitFullscreen) {
            document.exitFullscreen().then(resolve)
          } else if (document.webkitExitFullscreen) {
            document.webkitExitFullscreen().then(resolve)
          } else if (document.msExitFullscreen) {
            document.msExitFullscreen().then(resolve)
          } else {
            resolve()
          }
          // 关闭当前标签页
          this.$store.dispatch("tagsView/delView", this.$route)

          // 返回上一页
          this.$router.go(-1)
        } catch (error) {
          console.error('退出全屏失败:', error)
          resolve()
        } finally {
          this.isFullscreen = false
        }
      })
    },

    // 修改全屏变化处理
    handleFullscreenChange() {
      const wasFullscreen = this.isFullscreen
      this.isFullscreen = !!(
        document.fullscreenElement ||
        document.webkitFullscreenElement ||
        document.msFullscreenElement
      )

      // 如果从全屏变为非全屏
      if (wasFullscreen && !this.isFullscreen) {
        // 关闭当前标签页
        this.$store.dispatch("tagsView/delView", this.$route)
        // 返回上一页
        this.$router.go(-1)
      }
    },

    // 强制隐藏浏览器UI元素
    forceHideBrowserUI() {
      // 延迟执行确保全屏已激活
      setTimeout(() => {
        this.styleElement = document.createElement('style')
        this.styleElement.id = 'fullscreen-override'
        this.styleElement.textContent = `
          /* 隐藏滚动条 */
          ::-webkit-scrollbar {
            display: none !important;
          }

          /* 强制填满空间 */
          html, body {
            width: 100% !important;
            height: 100% !important;
            overflow: hidden !important;
          }

          /* 针对不同浏览器的隐藏策略 */
          :-webkit-full-screen {
            background: #fff;
          }

          :-moz-full-screen {
            background: #fff;
          }

          :-ms-fullscreen {
            background: #fff;
          }

          :fullscreen {
            background: #fff;
          }
        `
        document.head.appendChild(this.styleElement)
      }, 300)
    },

    // 创建全屏样式
    createFullscreenStyles() {
      // 防止重复创建
      if (this.styleElement) return

      this.styleElement = document.createElement('style')
      this.styleElement.id = 'fullscreen-override'
      this.styleElement.textContent = `
        .fullscreen-wrapper.is-fullscreen {
          position: fixed !important;
          top: 0 !important;
          left: 0 !important;
          width: 100vw !important;
          height: 100vh !important;
          z-index: 9999 !important;
          background: #fff !important;
          overflow: auto !important;
        }
      `
      document.head.appendChild(this.styleElement)
    },

    // 移除全屏样式
    removeFullscreenStyles() {
      if (this.styleElement) {
        document.head.removeChild(this.styleElement)
        this.styleElement = null
      }

      if (this.overlayElement) {
        document.body.removeChild(this.overlayElement)
        this.overlayElement = null
      }
    },

    // 备用全屏方案
    fallbackFullscreen() {
      this.isFullscreen = true
      document.body.style.overflow = 'hidden'

      // 创建遮罩层防止访问其他内容
      this.overlayElement = document.createElement('div')
      this.overlayElement.id = 'fullscreen-overlay'
      Object.assign(this.overlayElement.style, {
        position: 'fixed',
        top: '0',
        left: '0',
        width: '100vw',
        height: '100vh',
        backgroundColor: '#fff',
        zIndex: '9998'
      })
      document.body.appendChild(this.overlayElement)
    },

    // 移除所有事件监听
    removeEventListeners() {
      document.removeEventListener('fullscreenchange', this.handleFullscreenChange)
      document.removeEventListener('webkitfullscreenchange', this.handleFullscreenChange)
      document.removeEventListener('msfullscreenchange', this.handleFullscreenChange)

      if (this.visibilityChangeListener) {
        document.removeEventListener('visibilitychange', this.visibilityChangeListener)
      }

      if (this.blurListener) {
        window.removeEventListener('blur', this.blurListener)
      }

      if (this.focusListener) {
        window.removeEventListener('focus', this.focusListener)
      }
    },

    // 提供给父组件的手动全屏切换
    toggleFullscreen() {
      if (this.isFullscreen) {
        this.handleExitRequest()
      } else {
        this.enterFullscreen()
      }
    }
  },
  emits: ['cheating-detected', 'fullscreen-exited']
}
</script>

<style scoped>
.fullscreen-wrapper {
  position: relative;
  height: 100%;
}

.fullscreen-wrapper.is-fullscreen {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  z-index: 9999;
  background: #fff;
  overflow: auto;
}

.fullscreen-exit-btn {
  position: fixed;
  bottom: 20px;
  right: 20px;
  z-index: 10000;
  padding: 8px 16px;
  background-color: rgba(0, 0, 0, 0.7);
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 5px;
}

.fullscreen-exit-btn:hover {
  background-color: rgba(0, 0, 0, 0.9);
}

.fullscreen-exit-btn i {
  font-size: 16px;
}

.exit-confirm-content {
  display: flex;
  align-items: center;
  justify-content: center;
}

.switch-warning-content {
  display: flex;
  align-items: center;
}
</style>
